package com.froggyware.tadpole.core.impl;

import com.froggyware.tadpole.TadObject;
import com.froggyware.tadpole.core.DataStore;
import com.froggyware.tadpole.core.DataStoreConfigurator;
import com.froggyware.tadpole.util.FileSystem;

import java.io.File;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Steven
 * Date: 10/09/11
 * Time: 16:04
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbstractDataStore implements DataStore {

    private final static Logger LOGGER = Logger.getLogger(AbstractDataStore.class.getName());


    // TODO make configurable
    private final static String DEFAULT_ROOT_LOCATION="tadpole-data-store";
    protected boolean enableCompression=false;
    protected DataStoreConfigurator configurator;

    public DataStoreConfigurator getConfigurator() {
        return configurator;
    }

    public void setConfigurator(DataStoreConfigurator configurator) {
        this.configurator = configurator;
    }

    /**
     * The default is tadpole-data-store, this will be created wherever you run the app.
     * Provides the complete path.
     */
    protected String getFileDirectory(Object t) {

        String directory = getRootDirectory() + File.separator+getObjectName(t);


        // Check if the file structure exists or not
        FileSystem.createDir(new File(directory));

        return directory;
    }

    /**
     * The root directory of the data store
     * @return
     */
    protected String getRootDirectory() {

        if(configurator != null && configurator.getTarget() != null) {
            // not set then we just use this funny default, then at least it "might" work.
            return configurator.getTarget();
        }

        LOGGER.warning("No directory has been defined, using default = "+ DEFAULT_ROOT_LOCATION);
        return DEFAULT_ROOT_LOCATION;
    }


    @Override
    public abstract void write(TadObject t);


    /**
     * We don't use the package name as developers refactor their code all the time.
     * @param cls
     * @return
     */
    private String getObjectName(Object cls) {

        String name;

        // TODO this is all not mature.. Class should never come here.
        if(cls instanceof Class) {
            name = ((Class) cls).getName();
        } else {
            name = cls.getClass().getName();
        }
        //name = name.replace('.', '_');
        if (name.lastIndexOf('.') > 0) {
            name = name.substring(name.lastIndexOf('.')+1);  // Map$Entry
        }

        return name;
    }


    public void enableCompression(boolean b) {
        enableCompression=b;
    }


}
